<template>
	<view class="videos-container">
		<!-- 播放视频区域 -->
		<view class="video-box">
			<!-- #ifdef H5 -->
			<view id="videos" style="width: 100%;height: 100%;"></view>
			<!-- #endif  -->
			<!-- #ifdef APP-PLUS -->
			<video id="myVideo" :src="videoInfo.video" :poster="videoInfo.img" play-strategy=2 enable-play-gesture
				show-mute-btn autoplay controls style="width: 100%;height: 100%;"></video>
			<!-- #endif  -->
		</view>
		<!-- 滚动区域 -->
		<scroll-view scroll-y class="scroll-box" @scrolltolower="onLower">
			<view class="videoInfo">
				<view class="name">
					{{videoInfo.name}}
				</view>
				<view class="desc">
					{{videoInfo.desc}}
				</view>
				<view class="grey">
					<text class="num">
						观看次数：{{videoInfo.clickNum}}
					</text>
					<text class="num">
						影片时长：{{ videoInfo.duration}}
					</text>
					<text class="num">
						评分：{{videoInfo.score}}
					</text>
				</view>
			</view>
			<view class="type-title">
				<view style="display: flex;line-height: 50rpx;">
					<image style="width: 50rpx;height: 50rpx;" src="../../static/images/new.png"></image>
					<text style="margin-left: 10rpx;">猜你喜欢</text>
				</view>
			</view>
			<!-- 轮播图 -->
			<!-- <swiper :indicator-dots="false" :autoplay="true" :interval="5000" :circular="true" class="swiper">
				<swiper-item v-for="(_item,_index) in moreDatas.largePicture" style="width: 100%;height: 300rpx;">
					<image @click="onToVideos(_item)" :src="_item.img" class="swiper-img" mode="aspectFill"></image>
				</swiper-item>
			</swiper> -->
			<!-- 视频列表 -->
			<view class="video-list-box">
				<!-- <template v-if="topAdvertise.length">
					<view v-for="(_item,_index) in topAdvertise" @click="onJump(_item,1)" :key="_index"  class="video-list">
						<image :src="_item.remoteUrl?_item.remoteUrl:(resourceUrl + _item.img)"
							 class="img" mode="aspectFill">
						</image>
						<view class="text-ellipsis" >{{_item.desc || ""}}</view>
					</view>
				</template> -->
				<template v-for="(_item,_index) in datas">
					<view v-if="!(_index ===datas.length - 1 && topAdvertise.length % 2 === 1)" @click="onToVideos(_item)" :key="_index" class="video-list">
						<image :src="_item.img" class="img" mode="aspectFill">
						</image>
						<view class="text-ellipsis">{{_item.name}}</view>
					</view>
				</template>
			</view>
			<view v-if="bottomAdvertise.img || bottomAdvertise.remoteUrl" style="height: 120rpx;" />
		</scroll-view>
		<tui-toast ref="toast"></tui-toast>
		<view class="bottom">
			<view class="btn">
				<tui-button type="warning" width="200rpx" height="80rpx" style="margin-right: 20rpx;"><uni-icons
						type="redo" size="20" color="#ffffff"></uni-icons>分享</tui-button>
				<!-- <tui-button type="green" width="200rpx" height="80rpx" @click="handleCollect">收藏</tui-button> -->
				<uni-fav :checked="checkStore" class="favBtn" bg-color="#d6d6d6" bg-color-checked="#07c160"
					fg-color="#333333" fg-color-checked="#ffffff" @click="handleCollect" />
			</view>
		</view>
			<MyUseOut :showModal="isUseOut" @close="isUseOut=false" />
	</view>
</template>

<script>
	// #ifdef H5
	import Hls from "hls.js"
	import Dplayer from "dplayer"
	// #endif
	import { videoInfo ,playVideoNums,collectList,addCollect,configData,popularity} from '@/api/home.js'
	export default {
		data() {
			return {
				checkStore: false, //收藏
				isUseOut: false, //
				_id: "",
				// 更多视频
				moreDatas: {
					largePicture: [],
					datas: []
				},
				// 视频详细信息
				videoInfo: {},
				dp: {},
				// 顶部广告
				topAdvertise: [],
				// 广告
				bottomAdvertise: {},
				userInfo: {},
				page: 1,
				count: 0,
				datas: []
			}
		},
		onLoad(event) {
			this._id = event.id;
			// 如果是从本页面的MyUseOut弹框进入三种增加次数的页面去了，并且成功后，再跳转到本页面要默认关闭弹窗
			uni.$on('closeModal',data=>{
				this.isUseOut=data
			})
		},
		onShow() {
			this.userInfo = JSON.parse(localStorage.getItem('userInfo'))
		},
		onUnload() {
			// 页面销毁时移除监听，防止重复绑定
			uni.$off('closeModal');
		},
		mounted() {
			if (this._id) {
				this.doGetVideoInfo();
				this.doGetAdvertise();
				this.isCollect()
			} else {
				uni.switchTab({
					url: '/pages/watchMovie/index'
				});
			}
		},
		methods: {
			doGetAdvertise() {
				configData( {
					type: 4
				}).then(res => {
					this.topAdvertise = res.data.advertise.top || [];
					this.bottomAdvertise = res.data.advertise.bottom || {};
				})
			},
			// 获取视频信息
			doGetVideoInfo() {
				videoInfo( {
					_id: this._id,
					page: this.page
				}).then(res => {
					let data = res.data
					this.datas = data.datas
					this.count = data.count
					this.videoInfo = data.videoInfo;
					uni.setNavigationBarTitle({
						title: this.videoInfo.name
					});

					// 添加历史记录
					this.addHistoryList(this._id)
					// #ifdef H5
					this.videos(this.videoInfo.video);
					// #endif
				})
			},
			onLower() {
				
				if (this.datas.length < this.count) {
					this.page += 1;
					this.doGetVideoInfo();
				} else {
					this.showTips()
				}
			},
			showTips(e) {
				let options = {
					title: '我是有底线的啦~',
					icon: false
				};
				//需等组件初始化完成，确认已获取到组件实例
				this.$refs.toast && this.$refs.toast.show(options);
			},
			// 添加历史记录
			addHistoryList(vidId) {
				playVideoNums({
					userId: this.userInfo._id,
					vidId
				}).then(res => {
					uni.setStorageSync('infinite',res.data)
				})
			},
			// 是否收藏该部影片
			isCollect() {
				collectList({
					page: this.page,
					_id: this.userInfo._id,
					vidId: this._id
				}).then(res => {
					this.checkStore = Boolean(res.data.count)
				});
			},
			// 点击收藏
			handleCollect() {
				addCollect( {
					userId: this.userInfo._id,
					vidId: this._id
				}).then(res => {
					this.checkStore = !this.checkStore
					console.log('收藏', res);
				})
			},
			// 观看其他视频
			onToVideos(item) {
				this._id = item._id;
				if(!uni.getStorageSync('infinite')) {
					this.isUseOut=true
					return
				}
				this.doGetVideoInfo();
				
			},
			videos() {
				let dp = new Dplayer({
					container: document.getElementById("videos"),
					autoplay: true, //是否自动播放
					theme: "#000", //主题色
					loop: false, //视频是否循环播放
					lang: "zh-cn",
					screenshot: false, //是否开启截图
					hotkey: true, //是否开启热键
					preload: "metadata", //视频是否预加载
					// volume:0.6,//默认音量
					mutex: true, //阻止多个播放器同时播放，当前播放器播放时暂停其他播放器
					video: {
						url: this.videoInfo.video,
						pic: this.videoInfo.img,
						type: 'customHls',
						customType: {
							customHls: function(video, player) {
								const hls = new Hls({
									// 最大缓存的片段数量
									maxBufferLength: 60,
									// 最大缓存的时长（秒）
									maxBufferSize: 300 * 1024 * 1024,
									// 缓存中保留的最小片段数量
									maxBufferHole: 0.5,
									// 提前加载的片段数量
									nudgeMaxRetry: 3,
									// 加载片段失败后的重试次数
									startFragPrefetch: true,
								});
								hls.loadSource(video.src);
								hls.attachMedia(video);
							},
						},
					}
				})
				// dp.play()
			},
			/**
			 * 跳转
			 * @param {Object} item
			 * @param {Object} type  1：广告，2：app
			 */
			onJump(item, type) {
				let url = item.href;
				popularity( {
					type,
					_id: item._id
				})
				let isApp = true;
				// #ifdef H5
				isApp = false;
				// #endif
				if (isApp) {
					plus.runtime.openURL(url)
				} else {
					if (/Safari/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent)) {
						window.location.href = url;
					} else {
						window.open(url);
					}
				}
			},
		},
	}
</script>


<style scoped lang="scss">
	page {
		overflow-y: hidden;
	}

	.videos-container {
		margin: 20rpx;
		height: calc(100vh - var(--window-top) - 40rpx);

		.video-box {
			width: 100%;
			height: 400rpx;
		}

		.scroll-box {
			width: 100%;
			height: calc(100% - 500rpx);

			.videoInfo {
				padding: 20rpx 0;

				.name {
					font-weight: bold;
					margin-bottom: 20rpx;
				}

				.desc {
					font-size: 24rpx;
				}

				.grey {
					padding: 10rpx 10rpx 0 0;
					display: flex;
					justify-content: space-between;
				}

				.num {
					font-size: 24rpx;
					color: #949494;
				}
			}

			.type-title {
				width: 100%;
				display: flex;
				margin-top: 20rpx;
			}

			.swiper {
				width: 100%;
				height: 300rpx;
				margin-top: 20rpx;

				.swiper-img {
					width: 100%;
					height: 100%;
					border-radius: 20rpx;
				}
			}

			.video-list-box {
				display: flex;
				flex-wrap: wrap;
				margin-top: 20rpx;

				.video-list {
					width: 335rpx;
					text-align: center;
					padding: 10rpx;

					.img {
						width: 100%;
						height: 170rpx;
						border-radius: 10rpx;
					}

					.text-ellipsis {
						font-size: 26rpx;
					}
				}
			}
		}

		.bottom {
			position: absolute;
			width: 100vw;
			height: 100rpx;
			bottom: 0;
			left: 0;
			z-index: 99;
			background-color: transparent;

			.btn {
				display: flex;
				justify-content: center;
			}

			.favBtn {
				width: 200rpx;
				height: 80rpx;
				background-color: #07c160;
			}

		}
	}

	::v-deep .uni-fav-text {
		font-size: 32rpx !important;
		color: #ffffff;
	}

	::v-deep .uni-fav-star {
		font-size: 40rpx !important;
	}
</style>